package com.wang.userscenter.controller.back;

import com.alibaba.fastjson2.JSONObject;
import com.wang.userscenter.common.controller.BaseController;
import com.wang.userscenter.common.util.ConstatFinalUtil;
import com.wang.userscenter.common.util.DateUtil;
import com.wang.userscenter.common.util.PageInfoUtil;
import com.wang.userscenter.users.pojo.Aadmins;
import com.wang.userscenter.users.pojo.Arole;
import com.wang.userscenter.users.service.UsersDbService;
import jakarta.servlet.ServletException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 放一些模块相关的功能;一般来说是一个模块一个Servlet
 * 
 */
@Controller
@RequestMapping(value = "/back/UsersBack")
public class UsersBackController extends BaseController{
	@Autowired
	private UsersDbService usersDbService;
	/**
	 * 查询角色列表
	 */
	@RequestMapping("/roleList")
	public String roleList(String currentPage, String pageSize,
			String keyword, String status, String stDateStr, String edDateStr,
			Model model)
	{
		log.info("==角色列表页面==");
		String path = "/back/users/roleList";
		log.info("==分页信息==当前页:{},每页条数:{}", currentPage, pageSize);
		
		/* 分页 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		/* 因为分页要的是整数
		 * 从页面接收的参数有以下几种情况:
		 * 不传,就是null
		 * 传了,是非数字
		 * 肯定是无法保存为数字的.
		 * 使用try catch解决;
		 * 因为PageInfoUtil创建的对象有默认值,做容错处理 */
		try {
			pageInfoUtil.setPageSize(Integer.parseInt(pageSize));
			pageInfoUtil.setCurrentPage(Integer.parseInt(currentPage));
		} catch (NumberFormatException e) {
		}
		
		/* 从请求头中获取信息 */
		log.info("==搜索信息==keyword:{},status:{},stDateStr:{},edDateStr:{}", keyword,  status, stDateStr, edDateStr);
		/* 搜索条件 */
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		/* 关键字 */
		condMap.put("keyword", keyword);
		/* 状态 */
		condMap.put("status", status);
		/* 时间范围 */
		Date stDate = this.dateUtil.strToDate(stDateStr);
		Date edDate = this.dateUtil.strToDate(edDateStr);
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		/* 排序 */
		condMap.put("orderBy", "idDesc");
		List<Arole> roleList = this.usersDbService.selectRoleList(pageInfoUtil,condMap);
		/* 要把service中的结果数据放到四大作用域中 */
		model.addAttribute("roleList", roleList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		model.addAttribute("keyword", keyword);
		model.addAttribute("status", status);
		model.addAttribute("stDate", stDateStr);
		model.addAttribute("edDate", edDateStr);
		return path;
	}

	/**
	 * 管理员批量操作
	 */
	@RequestMapping("/adminsBatch")
	public String adminsBatch(String[] idsArr, String status) 
	{
		log.info("==adminsBatch==");
		String resultInfo = "";
		String info = "总条数:%s,成功条数:%s,失败条数:%s";
		/* 接受选择的复选框 */
		/* 接受选择的状态 */
		log.info("=idsArr===" + Arrays.toString(idsArr));
		if(idsArr != null) {
			/* 成功条数 */
			int succedCount = 0 ; 
			/* 失败条数 */
			int failedCount = 0 ; 
			for(int i = 0 ; i < idsArr.length ; i ++) {
				String id = idsArr[i];
				/* 现根据id查询管理员对象 */
				Map<String,Object> condMap = new HashMap<>();
				condMap.put("id", id);
				Aadmins admins = this.usersDbService.selectAdminsOne(condMap);
				if (admins != null) {
					admins.setStatus(Byte.valueOf(status));
					/* 更新数据库 */
					JSONObject dbJson = this.usersDbService.updateAdminsOne(admins);
					if (ConstatFinalUtil.INFO_STR_SUCCESS.equalsIgnoreCase(dbJson.getString(ConstatFinalUtil.INFO_STR_CODE))) {
						/* 成功 */
						succedCount ++;
					}
				} else {
					failedCount ++;
				}
			}
			resultInfo = String.format(info, idsArr.length, succedCount, failedCount);
		} else {
			resultInfo = "请勾选";
		}
		log.info(resultInfo);
		/* 要给相应 */
		return "redirect:/back/UsersBack/adminsList";
	}

	/**
	 * 提交管理员重置密码
	 
	 
	 * @throws IOException 
	 */
	@RequestMapping("/adminsUpdateResetPassSubmit")
	@ResponseBody
	public String adminsUpdateResetPassSubmit(String id,String password,Model model) {
		log.info("==adminsUpdateSubmit==");
		/* new对象 */
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		condMap.put("id", id);
		Aadmins admins = this.usersDbService.selectAdminsOne(condMap);
		model.addAttribute("admins", admins);
		/* 赋值 */
		admins.setPassword(password);
		/* 调用Service的方法入库 */
		JSONObject resultJson = this.usersDbService.updateAdminsOne(admins);
		return resultJson.toJSONString();
	}

	/**
	 * 打开管理员重置密码
	 
	 
	 * @throws IOException 
	 * @throws ServletException
	 */
	@RequestMapping("/adminsUpdateResetPass")
	public String adminsUpdateResetPass(int id,Model model)  {
		log.info("==adminsUpdate==");
		String path = "/back/users/adminsUpdateResetPass";
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		condMap.put("id", id);
		Aadmins admins = this.usersDbService.selectAdminsOne(condMap);
		model.addAttribute("admins", admins);
		return path;
	}

	/**
	 * 用户在管理员添加页面录入信息后,点击提交
	 
	 
	 * @throws IOException 
	 */
	@RequestMapping(value = "/adminsUpdateSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String adminsUpdateSubmit(Aadmins adminsReq, 
			MultipartFile photoFile,
			Model model) throws IOException {
		log.info("==adminsUpdateSubmit==");
		/* new对象 */
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		condMap.put("id", adminsReq.getId());
		Aadmins admins = this.usersDbService.selectAdminsOne(condMap);
		model.addAttribute("admins", admins);
		/* 赋值 */
		admins.setRoleId(adminsReq.getRoleId());
		admins.setEmail(adminsReq.getEmail());
		admins.setNickName(adminsReq.getNickName());
		admins.setTrueName(adminsReq.getTrueName());
		admins.setPhone(adminsReq.getPhone());
		admins.setQq(adminsReq.getQq());
		admins.setWeChat(adminsReq.getWeChat());
		admins.setStatus(adminsReq.getStatus());
		/* 处理文件
		 * 网络路径
		 * 真实路径
		 * 相对路径:/uploadfiles/日期/uuid.png
		 *  */
		String souRelaPath = admins.getPhotoPath();
		String truePath = ConstatFinalUtil.SYS_CONFIG_JSON.getString(ConstatFinalUtil.INFO_TRUEPATH);
		String relaPath = ConstatFinalUtil.SYS_CONFIG_JSON.getString(ConstatFinalUtil.INFO_RELAPATH);
		String fileName = photoFile.getOriginalFilename();
		relaPath = relaPath + "/" + this.dateUtil.dateToStr(new Date(), DateUtil.DATE_FORMAT) + "/" +  
				UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
		File trueFile = new File(truePath + relaPath);
		log.info("文件路径:{}", trueFile.getAbsolutePath());
		if (!trueFile.getParentFile().exists()) {
			/* 创建父目录 */
			trueFile.getParentFile().mkdirs();
		}
		photoFile.transferTo(trueFile);
		
		admins.setPhotoPath(relaPath);
		/* 调用Service的方法入库 */
		JSONObject resultJson = this.usersDbService.updateAdminsOne(admins);
		File oldFile = new File(truePath + souRelaPath);
		if (oldFile.exists()) {
			oldFile.delete();
			log.info("原文件删除成功:{}", oldFile.getAbsolutePath());
		}
		/* 返回json给客户端 */
		return resultJson.toJSONString();
	}

	/**
	 * 打开管理员更新页面
	 
	 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsUpdate")
	public String adminsUpdate(int id,String operType,Model model)  {
		log.info("==adminsUpdate==");
		String path = "/back/users/adminsInfo";
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		condMap.put("id", id);
		Aadmins admins = this.usersDbService.selectAdminsOne(condMap);
		model.addAttribute("admins", admins);
		
		/* 接受一个参数 */
		if ("updateInfo".equalsIgnoreCase(operType)) {
			/* 查询所有的角色 */
			/* 搜索条件 */
			condMap.clear();
			/* 状态 */
			condMap.put("status", "1");
			List<Arole> roleList = this.usersDbService.selectRoleList(null,condMap);
			model.addAttribute("roleList", roleList);
			path = "/back/users/adminsUpdate";
		}
		return path;
	}

	/**
	 * 用户在管理员添加页面录入信息后,点击提交
	 
	 
	 * @throws Exception 
	 * @throws IOException 
	 */
	@RequestMapping(value="/adminsInsertSubmit",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String adminsInsertSubmit(Aadmins admins) throws Exception{
		log.info("==adminsInsertSubmit==");
		/* 调用Service的方法入库 */
		JSONObject resultJson = this.usersDbService.saveAdminsOne(admins);
		/* 返回json给客户端 */
		return resultJson.toJSONString();
	}

	/**
	 * 打开管理员添加页面
	 
	 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsInsert")
	public String adminsInsert(Model model)  {
		log.info("==adminsInsert==");
		String path = "/back/users/adminsInsert";
		/* 查询所有的角色 */
		/* 搜索条件 */
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		/* 状态 */
		condMap.put("status", "1");
		List<Arole> roleList = this.usersDbService.selectRoleList(null,condMap);
		model.addAttribute("roleList", roleList);
		return path;
	}

	/**
	 * 管理员列表页面
	 
	 
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping("/adminsList")
	public String adminsList(String currentPage, String pageSize,
			String keyword, String status, String stDateStr, String edDateStr,String roleId,
			Model model)  {
		log.info("==管理员列表页面==");
		String path = "/back/users/adminsList";
		/* 从请求头中获取信息 */
		log.info("==分页信息==" + currentPage + "===" + pageSize);
		
		/* 分页 */
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		/* 因为分页要的是整数
		 * 从页面接收的参数有以下几种情况:
		 * 不传,就是null
		 * 传了,是非数字
		 * 肯定是无法保存为数字的.
		 * 使用try catch解决;
		 * 因为PageInfoUtil创建的对象有默认值,做容错处理 */
		try {
			pageInfoUtil.setPageSize(Integer.parseInt(pageSize));
			pageInfoUtil.setCurrentPage(Integer.parseInt(currentPage));
		} catch (NumberFormatException e) {
		}
		
		/* 从请求头中获取信息 */
		log.info("==搜索信息==" + keyword + "===" + status + "===" + stDateStr + "===" + edDateStr);
		/* 搜索条件 */
		Map<String,Object> condMap = new HashMap<String, Object>(1);
		/* 关键字 */
		condMap.put("keyword", keyword);
		/* 状态 */
		condMap.put("status", status);
		/* 时间范围 */
		Date stDate = this.dateUtil.strToDate(stDateStr);
		Date edDate = this.dateUtil.strToDate(edDateStr);
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);
		condMap.put("roleId", roleId);
		/* 排序 */
		condMap.put("orderBy", "idDesc");
		List<Aadmins> adminsList = this.usersDbService.selectAdminsList(pageInfoUtil,condMap);
		/* 要把service中的结果数据放到四大作用域中 */
		model.addAttribute("adminsList", adminsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		model.addAttribute("keyword", keyword);
		model.addAttribute("status", status);
		model.addAttribute("roleId", roleId);
		model.addAttribute("stDate", stDateStr);
		model.addAttribute("edDate", edDateStr);
		
		/* 搜索条件 */
		condMap.clear();
		/* 状态 */
		condMap.put("status", "1");
		List<Arole> roleList = this.usersDbService.selectRoleList(null,condMap);
		model.addAttribute("roleList", roleList);
		return path;
	}
}
